package com.easyexcle.demo.easyExcel.util;

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.time.temporal.IsoFields;
import java.util.*;

/**
 * @Author: lkz
 * @Title: WeekGroupOverDate
 * @Description: 按照周分组，不满一周补齐 可用
 * @Date: 2023/5/20 14:28
 */

public class WeekGroupOverDate {

    public static Map<Integer, List<LocalDate>> groupByWeek(List<LocalDate> dates) {
        Map<Integer, List<LocalDate>> weeklyGroups = new LinkedHashMap<>();

        // 遍历每一个日期，将其加入对应的周分组中
        for (LocalDate date : dates) {
            int weekOfYear = date.get(IsoFields.WEEK_OF_WEEK_BASED_YEAR);
            List<LocalDate> weekDates = weeklyGroups.get(weekOfYear);
            if (weekDates == null) {
                weekDates = new ArrayList<>();
                weeklyGroups.put(weekOfYear, weekDates);
            }
            weekDates.add(date);
        }

        return weeklyGroups;
    }

    public static void main(String[] args) {

        // 定义开始时间和结束时间
        LocalDate start = LocalDate.of(2023, 5, 1);
        LocalDate end = LocalDate.of(2023, 5, 31);

        // 生成时间段内的周一到周五的日期，并补齐一周
        List<LocalDate> weekdays = new ArrayList<>();
        long diffInDays = ChronoUnit.DAYS.between(start, end);
        for (int i = 0; i <= diffInDays; i++) {
            LocalDate date = start.plusDays(i);
            DayOfWeek dayOfWeek = date.getDayOfWeek();
            if (dayOfWeek != DayOfWeek.SATURDAY && dayOfWeek != DayOfWeek.SUNDAY) {
                weekdays.add(date);
            }
        }
        int weekdayCount = weekdays.size();
        if (weekdayCount > 0) {
            LocalDate lastWeekday = weekdays.get(weekdayCount - 1);
            DayOfWeek lastDayOfWeek = lastWeekday.getDayOfWeek();
            int daysToAdd = 5 - lastDayOfWeek.getValue();
            for (int i = 1; i <= daysToAdd; i++) {
                LocalDate dateToAdd = lastWeekday.plusDays(i);
                weekdays.add(dateToAdd);
            }
        }

        // 将日期按周分组，并输出结果
        Map<Integer, List<LocalDate>> weeklyGroups = groupByWeek(weekdays);
        for (Map.Entry<Integer, List<LocalDate>> entry : weeklyGroups.entrySet()) {
            int weekOfYear = entry.getKey();
            List<LocalDate> weekDates = entry.getValue();
            System.out.println("第 " + weekOfYear + " 周：");
            for (LocalDate date : weekDates) {
                System.out.println(date.toString());
            }
            System.out.println();
        }

    }



}
